import * as vscode from 'vscode';
import * as moment from 'moment';
import { CommitSummary, FeaturePoint } from './summaryGenerator';

export class SummaryViewProvider {
    private panel: vscode.WebviewPanel | undefined;
    
    constructor(private readonly extensionUri: vscode.Uri) {}
    
    /**
     * Shows the loading state in the webview panel
     */
    public showLoading(): void {
        const title = "Git Summary";
        
        // If we already have a panel, show it
        if (this.panel) {
            this.panel.reveal(vscode.ViewColumn.One);
            this.setLoadingContent();
            return;
        }
        
        // Otherwise, create a new panel
        this.panel = vscode.window.createWebviewPanel(
            'gitSummary',
            title,
            vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );
        
        // Set up a listener for when the panel is disposed
        this.panel.onDidDispose(() => {
            this.panel = undefined;
        }, null);
        
        this.setLoadingContent();
    }
    
    /**
     * Updates the webview panel with the summary content
     */
    public update(summary: CommitSummary, aiSummary: string | null = null, aiError: string | null = null): void {
        if (!this.panel) {
            this.show(summary, aiSummary, aiError);
            return;
        }
        
        this.updateContent(summary, aiSummary, aiError);
    }
    
    /**
     * Shows an error message in the webview panel
     */
    public showError(errorMessage: string): void {
        if (!this.panel) {
            // Create a new panel if one doesn't exist
            const title = "Git Summary";
            this.panel = vscode.window.createWebviewPanel(
                'gitSummary',
                title,
                vscode.ViewColumn.One,
                {
                    enableScripts: true,
                    retainContextWhenHidden: true
                }
            );
            
            this.panel.onDidDispose(() => {
                this.panel = undefined;
            }, null);
        }
        
        this.panel.reveal(vscode.ViewColumn.One);
        this.panel.webview.html = this.getErrorContent(errorMessage);
    }
    
    /**
     * Shows the summary content in the webview panel (original method, kept for backward compatibility)
     */
    public show(summary: CommitSummary, aiSummary: string | null = null, aiError: string | null = null): void {
        const title = "Git Summary";
        
        // If we already have a panel, show it
        if (this.panel) {
            this.panel.reveal(vscode.ViewColumn.One);
            this.updateContent(summary, aiSummary, aiError);
            return;
        }
        
        // Otherwise, create a new panel
        this.panel = vscode.window.createWebviewPanel(
            'gitSummary',
            title,
            vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );
        
        // Set up a listener for when the panel is disposed
        this.panel.onDidDispose(() => {
            this.panel = undefined;
        }, null);
        
        this.updateContent(summary, aiSummary, aiError);
    }
    
    private updateContent(summary: CommitSummary, aiSummary: string | null = null, aiError: string | null = null): void {
        if (!this.panel) {
            return;
        }
        
        this.panel.webview.html = this.getWebviewContent(summary, aiSummary, aiError);
    }
    
    private setLoadingContent(): void {
        if (!this.panel) {
            return;
        }
        
        this.panel.webview.html = this.getLoadingContent();
    }
    
    private getLoadingContent(): string {
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git Summary - Loading</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            padding: 0 20px;
            color: var(--vscode-foreground);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }
        .loading-container {
            text-align: center;
        }
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--vscode-progressBar-background);
            width: 40px;
            height: 40px;
            margin: 20px auto;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="loading-container">
        <h2>Generating Git Summary</h2>
        <div class="spinner"></div>
        <p>Please wait while we analyze your git repository...</p>
    </div>
    
    <script>
        // This script ensures the loading animation continues even if there's an error
        window.addEventListener('error', function(e) {
            console.error('Error occurred:', e.error);
            // Prevent the loading state from being stuck
            document.querySelector('.loading-container').innerHTML += 
                '<p style="color: var(--vscode-errorForeground);">An error occurred. Please try again.</p>';
        });
    </script>
</body>
</html>`;
    }
    
    private getErrorContent(errorMessage: string): string {
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git Summary - Error</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            padding: 20px;
            color: var(--vscode-foreground);
        }
        .error-container {
            padding: 20px;
            border-radius: 5px;
            background-color: var(--vscode-inputValidation-errorBackground);
            border: 1px solid var(--vscode-inputValidation-errorBorder);
            color: var(--vscode-errorForeground);
            margin-bottom: 20px;
        }
        h1 {
            color: var(--vscode-errorForeground);
        }
        .error-details {
            font-family: monospace;
            white-space: pre-wrap;
            margin-top: 10px;
            padding: 10px;
            background-color: var(--vscode-editor-background);
            border-radius: 3px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h1>Error Generating Git Summary</h1>
    <div class="error-container">
        <p>An error occurred while generating the git summary:</p>
        <div class="error-details">${errorMessage}</div>
    </div>
    <p>Please check the error message above and try again. If the problem persists, please check your git repository configuration.</p>
</body>
</html>`;
    }
    
    private getWebviewContent(summary: CommitSummary, aiSummary: string | null = null, aiError: string | null = null): string {
        const fromDate = moment(summary.period.from).format('YYYY-MM-DD');
        const toDate = moment(summary.period.to).format('YYYY-MM-DD');
        
        const features = summary.features.sort((a, b) => {
            // Sort by category first, then by title
            if (a.category !== b.category) {
                return a.category.localeCompare(b.category);
            }
            return a.title.localeCompare(b.title);
        });
        
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git Summary</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            padding: 0 20px;
            color: var(--vscode-foreground);
        }
        h1, h2, h3 {
            color: var(--vscode-editor-foreground);
        }
        .summary-header {
            margin-bottom: 20px;
        }
        .period {
            color: var(--vscode-descriptionForeground);
            font-size: 0.9em;
        }
        .stat {
            margin-right: 15px;
            display: inline-block;
        }
        .category-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            margin-left: 8px;
        }
        .FEATURE { background-color: #0366d6; color: white; }
        .FIX { background-color: #d73a49; color: white; }
        .REFACTOR { background-color: #6f42c1; color: white; }
        .DOC { background-color: #22863a; color: white; }
        .TEST { background-color: #e36209; color: white; }
        .STYLE { background-color: #6a737d; color: white; }
        .OTHER { background-color: #6a737d; color: white; }
        
        .feature-item {
            margin-bottom: 20px;
            padding: 10px;
            border-left: 4px solid #d1d5da;
        }
        .commit-list {
            font-size: 0.85em;
            margin-top: 5px;
            color: var(--vscode-descriptionForeground);
        }
        .commit-item {
            margin-top: 3px;
        }
        .commit-hash {
            font-family: monospace;
            color: var(--vscode-textLink-foreground);
        }
        .commit-date {
            color: var(--vscode-descriptionForeground);
        }
        .commit-author {
            font-style: italic;
        }
        .commit-message {
            display: block;
            margin-left: 10px;
        }
        .feature-section {
            margin-top: 30px;
        }
        .chart-container {
            margin: 20px 0;
            height: 200px;
        }
        details {
            margin-top: 5px;
        }
        summary {
            cursor: pointer;
        }
        .ai-summary {
            margin-top: 20px;
            padding: 15px;
            background-color: var(--vscode-editor-inactiveSelectionBackground);
            border-radius: 5px;
        }
        .ai-summary h2 {
            margin-top: 0;
        }
        .ai-error {
            color: var(--vscode-errorForeground);
            margin-bottom: 10px;
            padding: 10px;
            background-color: var(--vscode-inputValidation-errorBackground);
            border: 1px solid var(--vscode-inputValidation-errorBorder);
            border-radius: 5px;
        }
        .ai-error-details {
            font-family: monospace;
            white-space: pre-wrap;
            margin-top: 10px;
            padding: 10px;
            background-color: var(--vscode-editor-background);
            border-radius: 3px;
            max-height: 200px;
            overflow-y: auto;
        }
        .tab-container {
            margin-top: 20px;
        }
        .tab-buttons {
            display: flex;
            border-bottom: 1px solid var(--vscode-panel-border);
        }
        .tab-button {
            padding: 8px 16px;
            cursor: pointer;
            background: none;
            border: none;
            color: var(--vscode-foreground);
            font-size: 14px;
            outline: none;
        }
        .tab-button.active {
            border-bottom: 2px solid var(--vscode-focusBorder);
            font-weight: bold;
        }
        .tab-content {
            display: none;
            padding: 15px 0;
        }
        .tab-content.active {
            display: block;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        .stats-card {
            background-color: var(--vscode-editor-inactiveSelectionBackground);
            border-radius: 5px;
            padding: 15px;
            text-align: center;
        }
        .stats-card h3 {
            margin-top: 0;
            font-size: 14px;
            color: var(--vscode-descriptionForeground);
        }
        .stats-value {
            font-size: 24px;
            font-weight: bold;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="summary-header">
        <h1>Git Commit Summary</h1>
        <p class="period">Period: ${fromDate} to ${toDate}</p>
        
        <div class="stats-grid">
            <div class="stats-card">
                <h3>Total Commits</h3>
                <div class="stats-value">${summary.totalCommits}</div>
            </div>
            <div class="stats-card">
                <h3>Contributors</h3>
                <div class="stats-value">${summary.contributorCount}</div>
            </div>
            <div class="stats-card">
                <h3>Lines Added</h3>
                <div class="stats-value">${summary.lineStats.added}</div>
            </div>
            <div class="stats-card">
                <h3>Lines Deleted</h3>
                <div class="stats-value">${summary.lineStats.deleted}</div>
            </div>
            <div class="stats-card">
                <h3>Files Changed</h3>
                <div class="stats-value">${summary.lineStats.modified}</div>
            </div>
            <div class="stats-card">
                <h3>Total Lines</h3>
                <div class="stats-value">${summary.lineStats.total}</div>
            </div>
        </div>
        
        <div>
            ${Object.entries(summary.categories).map(([cat, count]) => 
                `<span class="stat">${cat}: ${count}</span>`
            ).join('')}
        </div>
    </div>
    
    ${aiSummary !== null ? `
    <div class="tab-container">
        <div class="tab-buttons">
            <button class="tab-button active" onclick="switchTab('ai-tab')">AI Summary</button>
            <button class="tab-button" onclick="switchTab('standard-tab')">Standard Summary</button>
        </div>
        
        <div id="ai-tab" class="tab-content active">
            <div class="ai-summary">
                <h2>AI-Generated Summary</h2>
                ${this.renderMarkdown(aiSummary)}
            </div>
        </div>
        
        <div id="standard-tab" class="tab-content">
            <h2>Product Change Points</h2>
            ${this.renderFeaturesByCategory(features)}
        </div>
    </div>
    ` : `
    ${aiError !== null ? `
        <div class="ai-error">
            <h3>AI Summary Generation Failed</h3>
            <p>The AI summary could not be generated due to the following error:</p>
            <div class="ai-error-details">${aiError}</div>
            <p>Please check your AI configuration or try again later.</p>
        </div>
    ` : `
        <div class="ai-error">
            <p>AI summary generation failed or is not configured. Showing standard summary instead.</p>
            <p>To configure AI, run the "Git Summary: Configure AI model" command.</p>
        </div>
    `}
    <h2>Product Change Points</h2>
    ${this.renderFeaturesByCategory(features)}
    `}
    
    <script>
        function switchTab(tabId) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Deactivate all buttons
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // Show the selected tab
            document.getElementById(tabId).classList.add('active');
            
            // Activate the clicked button
            event.target.classList.add('active');
        }
    </script>
</body>
</html>`;
    }
    
    private renderFeaturesByCategory(features: FeaturePoint[]): string {
        // Group features by category
        const featuresByCategory: Record<string, FeaturePoint[]> = {};
        
        for (const feature of features) {
            if (!featuresByCategory[feature.category]) {
                featuresByCategory[feature.category] = [];
            }
            featuresByCategory[feature.category].push(feature);
        }
        
        // Render each category section
        return Object.entries(featuresByCategory).map(([category, categoryFeatures]) => {
            return `
            <div class="feature-section">
                <h3>${category} Changes</h3>
                ${categoryFeatures.map(feature => this.renderFeatureItem(feature)).join('')}
            </div>
            `;
        }).join('');
    }
    
    private renderFeatureItem(feature: FeaturePoint): string {
        return `
        <div class="feature-item">
            <h4>${feature.title} <span class="category-badge ${feature.category}">${feature.category}</span></h4>
            <details>
                <summary>Show ${feature.commits.length} commits</summary>
                <div class="commit-list">
                    ${feature.commits.map(commit => `
                        <div class="commit-item">
                            <span class="commit-hash">${commit.hash.substring(0, 7)}</span>
                            <span class="commit-date">${moment(commit.date).format('YYYY-MM-DD')}</span>
                            <span class="commit-author">${commit.author}</span>
                            <span class="commit-message">${commit.message}</span>
                        </div>
                    `).join('')}
                </div>
            </details>
        </div>
        `;
    }
    
    private renderMarkdown(markdown: string): string {
        // Simple markdown to HTML conversion for the AI summary
        // This is a basic implementation - for production, consider using a proper markdown library
        
        // Convert headers
        let html = markdown
            .replace(/^### (.*$)/gim, '<h3>$1</h3>')
            .replace(/^## (.*$)/gim, '<h2>$1</h2>')
            .replace(/^# (.*$)/gim, '<h1>$1</h1>');
            
        // Convert lists
        html = html
            .replace(/^\* (.*$)/gim, '<ul><li>$1</li></ul>')
            .replace(/^- (.*$)/gim, '<ul><li>$1</li></ul>')
            .replace(/<\/ul><ul>/g, '');
            
        // Convert bold and italic
        html = html
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>');
            
        // Convert paragraphs
        html = html
            .replace(/^\s*$/gm, '</p><p>')
            .replace(/^(?!<[hou])/gm, '<p>$&')
            .replace(/<\/p><p>/g, '</p>\n<p>');
            
        return html;
    }
}
